import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export const useTodos = defineStore('todos', {
  state: () => ({
    /** @type { id:number,text:String } */
    todos: [
      {
        id: 1,
        text: '111',
        isFinished: false
      },
      {
        id: 2,
        text: '222',
        isFinished: false
      },
      {
        id: 3,
        text: '333',
        isFinished: true
      }
    ],
    /** @type {{ text: string, id: number, isFinished: boolean }[]}*/
    todo: {
      id: -1,
      text: '',
      isFinished: false
    },
    filter: 'all',
    nextId: 2,
    index: 1,
    dialogFormVisible: false
  }),
  getters: {
    filterTodos(state) {
      if (state.filter === 'unFinished') {
        return state.todos.filter((todos) => !todos.isFinished)
      } else if (state.filter === 'isFinished') {
        return state.todos.filter((todos) => todos.isFinished)
      }
      return state.todos
    },
    dialogTodos(state) {
      return state.dialogData
    }
  },
  // 也可以这样定义
  // state: () => ({ count: 0 })
  actions: {
    handleFinish(index, row) {
      row.isFinished = true
    },

    loadData() {
      this.todos.push({ text: 'text', id: this.index++, isFinished: false })
    },
    showDialog() {
      this.dialogFormVisible = true
    },
    closeDialog() {
      this.dialogFormVisible = false
    },
    save() {
      if (this.todo.id === -1) {
        this.todo.id = this.nextId++
        this.todos.push(JSON.parse(JSON.stringify(this.todo)))
      }
      console.log(this.todo)

      this.dialogFormVisible = false
    },
    handleAdd() {
      this.showDialog()
      this.todo.id = -1
    },
    handleEdit(index, row) {
      this.showDialog()
      this.index = index
      this.todo = JSON.parse(JSON.stringify(row))
    },
    handleDelete(index, row) {
      this.delete(index)
    },
    delete(index) {
      ElMessageBox.confirm(
        ` ${this.todos[index].text}       will permanently delete the file. Continue?'`,
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          ElMessage({
            type: 'success',
            message: 'Delete completed'
          })
          this.todos.splice(index, 1)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: 'Delete canceled'
          })
        })
    }
  }
})
